package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"net/http"
)

type Role struct {
	ID          uint         `json:"id" gorm:"primarykey"`
	Name        string       `json:"name"`
	Permissions []Permission `json:"permissions" gorm:"many2many:role_permissions;"`
}

type Permission struct {
	ID   uint   `json:"id" gorm:"primarykey"`
	Name string `json:"name"`
}

func main() {
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info), //Info(显示sql)  Silent
	})
	if err != nil {
		panic("failed to connect database")
	}

	// 自动迁移数据库
	db.AutoMigrate(&Role{}, &Permission{})

	r := gin.Default()
	r.StaticFS("/zk", http.Dir("dist"))

	// 获取所有权限
	r.GET("/api/permissions", func(c *gin.Context) {
		var permissions []Permission
		db.Find(&permissions)
		c.JSON(http.StatusOK, permissions)
	})
	// 获取所有角色
	r.GET("/api/roles", func(c *gin.Context) {
		var roles []Role
		db.Preload("Permissions").Find(&roles)
		c.JSON(http.StatusOK, roles)
	})

	// 创建角色
	r.POST("/api/roles", func(c *gin.Context) {
		var role Role
		c.BindJSON(&role)
		db.Create(&role)
		c.Status(http.StatusOK)
	})

	// 更新角色
	r.PUT("/api/roles/:id", func(c *gin.Context) {
		var role Role
		db.First(&role, c.Param("id"))
		c.BindJSON(&role)
		db.Save(&role)
		c.Status(http.StatusOK)
	})

	// 删除角色
	r.DELETE("/api/roles/:id", func(c *gin.Context) {
		var role Role
		db.Delete(&role, c.Param("id"))
		c.Status(http.StatusOK)
	})

	r.POST("/GetListData", func(c *gin.Context) {

		var body struct {
			Nr    string `json:"nr"`
			Page  int    `json:"page"`
			Size  int    `json:"size"`
			Sort  string `json:"sort"`
			Order string `json:"order"`
		}

		if err := c.BindJSON(&body); err != nil {
			return
		}
		fmt.Println("body,", body)

		name := "%" + body.Nr + "%"
		sql := fmt.Sprintf("name like '%s'", name)

		pageSize := body.Size
		page := body.Page
		sort := body.Sort
		order := body.Order
		offset := (page - 1) * pageSize

		sortStr := fmt.Sprintf("%s %s", sort, order)

		results_ := []Role{}
		resultsNum_ := []Role{}

		db.Where(sql).Offset(offset).Limit(pageSize).Order(sortStr).Find(&results_)
		var num int64
		db.Where(sql).Find(&resultsNum_).Count(&num)

		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "list",
			"data":    results_,
			"total":   num,
		})
	})

	r.Run(":8085")
}
